package com.zy.explore.common.infrastructure.aspect;

import com.zy.explore.common.infrastructure.annotation.LogCostTime;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * description 方法耗时切面
 * 注意，execution中的包路径！
 *
 * @author ChinaYin  主页:https://gitee.com/zy-explorej2ee 邮箱:zyexplorej2ee@sina.com
 * @date 2021年06月13日 14:13:45
 */
@Component
@Aspect
@Slf4j
public class TimeCostAspect {

    @Pointcut("execution(* com.zy.explore.application.service.*..*(..))")
    public void webLog() {
    }

    /**
     * 统计方法执行时间
     *
     * @author ChinaYin  主页:https://gitee.com/zy-explorej2ee 邮箱:zyexplorej2ee@sina.com
     * @date 2021/05/16
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        // result 为方法的返回值
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();

        Object target = pjp.getTarget();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        String className = target.getClass().getName();
        Method method = signature.getMethod();
        LogCostTime annotation = method.getAnnotation(LogCostTime.class);
        if (annotation != null) {
            // 方法名称
            String methodName = method.getName();
            log.info(">>>耗时统计：{}.{}  执行耗时：{}ms", className, methodName, (end - start));
        }
        return result;
    }

}